import { Injectable, Injector } from '@angular/core';
import { IdService } from '@farris/ui-common';
import { DomService, FormViewModel, FormSchemaEntity, FormSchemaEntityField, DesignerHostSettingService } from '@farris/designer-services';
import { DgControl } from '../../../../../../../utils/dg-control';
import { ControlService } from '../../../../../../../service/control.service';


@Injectable()
export class TableFillInFormTempalteService {

    private contents;
    private components;
    private selectedEntity: FormSchemaEntity;
    // private mainEntityLabel: string;

    private addBtnCode;
    private deleteBtnCode;

    controlCreatorService: any;
    constructor(
        private idService: IdService,
        private controlService: ControlService,
        designerHostService: DesignerHostSettingService,
        private domService: DomService) {
        this.controlCreatorService = designerHostService.designerHost.getService('ControlCreatorService');
    }

    resolveTemplate(domJson: any, selectedEntity: FormSchemaEntity, selectedFields: FormSchemaEntityField[]) {

        this.contents = domJson.contents;
        this.components = domJson.components;
        this.selectedEntity = selectedEntity;
        // this.mainEntityLabel = mainEntityLabel;

        this.setTitle();
        this.setSectionTitle();
        this.setTableColumns(selectedFields);

    }

    private setTitle() {
        const title = this.domService.selectNode(this.contents[0], (item) => item.id.startsWith('page-header-title'));
        if (title) {
            title.html = title.html.replace('${title}', this.selectedEntity.type.displayName);
        }

    }
    private setSectionTitle() {
        const section = this.domService.selectNode(this.components[0], item => item.type === DgControl.Section.type);
        if (section) {
            section.mainTitle = this.selectedEntity.type.displayName;
        }

    }
    private setTableColumns(selectedFields: FormSchemaEntityField[]) {
        const table = this.domService.selectNode(this.components[0], item => item.type === 'Table');
        if (!table) { return; }



        table.rows = [];
        // 计算table行数
        let rowCounts = selectedFields.length / 2 + 0.5;
        rowCounts = parseInt(rowCounts + '', 10);

        for (let rowIndex = 0, fieldCount = 0; rowIndex < rowCounts; rowIndex++) {
            let columns = [];
            for (let index = 0; index < 2; index++) {
                const field = fieldCount < selectedFields.length ? selectedFields[fieldCount] : null;
                const labelTds = this.createLabelTd(field);
                const editorTds = this.createEditorTd(field);
                columns = columns.concat(labelTds).concat(editorTds);

                fieldCount++;
            }

            table.rows.push({
                id: this.idService.generate(),
                type: 'TableRow',
                columns
            });

        }
    }


    private createLabelTd(field: any): any[] {
        const tdMetadata = this.controlService.getControlMetaData('TableTd');
        tdMetadata.tdType = 'staticText';
        tdMetadata.appearance.class = 'farris-group-wrap--label';
        tdMetadata.id = this.idService.generate();

        if (field) {
            tdMetadata.staticText.text = field.name;
            tdMetadata.staticText.require = field.require;
        }

        return [tdMetadata];
    }
    private createEditorTd(field: any) {
        // 可编辑单元格
        const tdMetadata = this.controlService.getControlMetaData('TableTd');
        tdMetadata.id = this.idService.generate();
        tdMetadata.tdType = 'editor';
        tdMetadata.colspan = 2;
        tdMetadata.appearance.class = 'farris-group-wrap--input';
        let metadata;
        if (field && field.editor) {
            metadata = this.controlCreatorService.createTableTdControlBySchemaFeild(field);
            tdMetadata.editor = metadata;
        }

        // 隐藏单元格
        const invisibleTd = this.controlService.getControlMetaData('TableTd');
        invisibleTd.id = this.idService.generate();
        invisibleTd.invisible = true;
        invisibleTd.markCol = 1;
        invisibleTd.markRow = 0;

        return [tdMetadata, invisibleTd];


    }


    /**
     * 将命令添加到视图模型
     * @param componentId 
     * @param bindTo 
     * @param templateId
     */
    addCommandsToTableViewModel(componentId: string, viewModel: FormViewModel) {
        const tableCode = this.selectedEntity.code.toLowerCase();
        // const tableLabel = this.selectedEntity.label;
        // let parentBindTo = '';
        // 从从表
        // if (viewModel.bindTo.lastIndexOf('/') > 0) {
        //     parentBindTo = viewModel.bindTo.slice(0, viewModel.bindTo.indexOf(tableLabel) - 1);
        // }
        this.addBtnCode = tableCode + 'Add' + Math.random().toString(36).slice(2, 6);
        this.deleteBtnCode = tableCode + 'Remove' + Math.random().toString(36).slice(2, 6);

        viewModel.commands = viewModel.commands.concat([
            {
                id: this.idService.generate(),
                code: this.addBtnCode,
                name: '增加一条子表数据',
                params: [],
                handlerName: 'AddItem',
                cmpId: '8172a979-2c80-4637-ace7-b13074d3f393',
                extensions: [
                ]
            },
            {
                id: this.idService.generate(),
                code: this.deleteBtnCode,
                name: '删除一条子表数据',
                params: [
                    {
                        name: 'id',
                        shownName: '数据id',
                        value: '{EVENTPARAM~/context/id}'
                    }
                ],
                handlerName: 'RemoveItem',
                cmpId: '8172a979-2c80-4637-ace7-b13074d3f393',
                extensions: []
            }]);

        // 在命令构件的引用信息中记录子表的命令对构件方法的引用。
        const webcmds = this.domService.getWebCmds();
        for (const command of viewModel.commands) {
            const webcmd = webcmds.find(item => item.id === command.cmpId);
            if (!webcmd) {
                continue;
            }
            webcmd.refedHandlers.push({ host: command.id, handler: command.handlerName });
        }
    }


    /**
     * 为批量编辑表格模板增加“删除”和“新增”命令，因为不确定模板最终应用的表单类型，所以没有在模板中定义这些命令
     */
    addCommandsToTableBatchComponent(viewModelId: string) {

        // 新增按钮是放在根组件上的，但命令是放在子组件里的，所以这里click绑定要增加路径信息
        const addBtn = this.domService.selectNode(this.contents[1], item => item.type === DgControl.Button.type && item.id.startsWith('add-btn'));
        if (addBtn) {
            addBtn.click = `root-viewmodel.${viewModelId}.${this.addBtnCode}`;

        }
        const section = this.domService.selectNode(this.components[0], item => item.type === DgControl.Section.type);
        if (section && section.toolbar && section.toolbar.contents) {
            section.toolbar.contents[0].click = this.deleteBtnCode;;
        }

    }

}
